package com.afd.ozblip.chat;

import java.net.InetSocketAddress;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.afd.ozblip.util.Constants;

import android.os.Handler;

public class ChatClient {
	private static ChatClient mainClient = null;

	IoSession session = null;
	String userId;

	public static ChatClient getInstances(String userId) {
		if (null == mainClient) {
			mainClient = new ChatClient(userId);
		}
		return mainClient;
	}

	private ChatClient(String userId) {
		this.userId = userId;
		System.setProperty("java.net.preferIPv6Addresses", "false");// 2.2会有ipv6的问题，
		SocketConnector connector = new NioSocketConnector();
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		chain.addLast("myChin", new ProtocolCodecFilter(
				new ObjectSerializationCodecFactory()));
		connector.setHandler(ClientHandler.getInstances(userId));
		connector.setConnectTimeoutMillis(30000);
		try {
			// ConnectFuture cf = connector.connect(new InetSocketAddress(
			// "192.168.1.3", 8888));
//			ConnectFuture cf = connector.connect(new InetSocketAddress(
//					"192.168.0.102", 8888));
			// ConnectFuture cf = connector.connect(new InetSocketAddress(
			// "103.28.204.76", 8888));
			ConnectFuture cf = connector.connect(new InetSocketAddress(
					Constants.SERVICE_IP, 8888));
			cf.awaitUninterruptibly();
			session = cf.getSession();
		} catch (RuntimeIoException e) {
			e.printStackTrace();
		}
		// session.getCloseFuture().awaitUninterruptibly();
		// connector.dispose();
	}

	public void sendMsgToUser(String toUId, String msg) {
		MinaEntity<String> sendMina = new MinaEntity<String>(
				MinaEntityType.MESSAGE);
		sendMina.setFromUser(this.userId);
		sendMina.setToUser(toUId);
		sendMina.setObject(msg);
		// String json = JSON.toJSONString(sendMina);
		session.write(sendMina);
	}

	public void setUIHandler(Handler uih) {
		ClientHandler.getInstances(userId).setUIHandler(uih);
	}

	public static void main(String args[]) {
		ChatClient.getInstances("2");
	}
}